#!/bin/sh

# if app not exist
if [ ! -f /bin/mdev ] || [ ! -f /proc/sys/kernel/hotplug ]; then
    exit 0
fi

LOG="echo HOTPLUG"

start() {
    if [ ! -f /etc/mdev.conf ]; then
	$LOG "Generate config file."
	printf "
	    # <device regex> <uid>:<gid> <octal permissions> [<@|$|*> <command>]
	    # The special characters have the meaning:
	    # @ Run after creating the device.
	    # $ Run before removing the device.
	    # * Run both after creating and before removing the device.\n" > /etc/mdev.conf
	if [ -d /proc/bus/usb ]; then
		echo "# usb device" >> /etc/mdev.conf
		echo "usbdev([0-9]+).([0-9])    0:0     0660  =bus/usb/00%1/00%2" >> /etc/mdev.conf
		echo "usbdev([0-9]+).([0-9]{2}) 0:0     0660  =bus/usb/00%1/0%2" >> /etc/mdev.conf
		echo "usbdev([0-9]+).([0-9]{3}) 0:0     0660  =bus/usb/00%1/%2" >> /etc/mdev.conf 
	    if [ -f /etc/scripts/automount.sh ] && [ -f /bin/blkid ]; then
		echo "sd[a-z][1-9] 0:0 0660 */etc/scripts/automount.sh" >> /etc/mdev.conf
	    fi
	    if [ -f /etc/scripts/usbctrl.sh ] && [ -f /bin/usb_modeswitch ]; then
		echo "1-.*:1.* 0:0 0000 @/etc/scripts/usbctrl.sh" >> /etc/mdev.conf
	    fi
	    if [ -f /etc/scripts/prnctrl.sh ] && [ -f /bin/p910nd ]; then
		echo "lp[0-9] 0:0 0660 */etc/scripts/prnctrl.sh" >> /etc/mdev.conf
	    fi
	    if [ -f /etc/scripts/modem.sh ]; then
		echo "ttyUSB[0-9] 0:0 0660 */etc/scripts/modem.sh $MDEV" >> /etc/mdev.conf
		echo "ttyACM[0-9] 0:0 0660 */etc/scripts/modem.sh $MDEV" >> /etc/mdev.conf
	    fi
	fi
    fi

    $LOG "Set mdev as kernel hotplug helper and enable device autoprobe."
    echo "/bin/mdev" > /proc/sys/kernel/hotplug

    if [ -d /proc/bus/usb ]; then
	# enable drivers autoprobe for all usb devices
	if [ -f /sys/bus/usb/drivers_autoprobe ]; then
	    echo 1 > /sys/bus/usb/drivers_autoprobe
	fi

	# touch uevent for cold start usb and other hotplug devices allready connected to SOC at boot
	find /sys -type f -name 'uevent' | while read dev_event; do
    	    echo 1 > $dev_event
	done
    fi
}

stop() {
 $LOG "Stop mdev generate..."
    killall -q mdev
    killall -q -SIGKILL mdev
}

case "$1" in
	start)
	    start
	    ;;

	stop)
	    stop
	    ;;

	restart)
	    stop
	    start
	    ;;

	*)
	    echo $"Usage: $0 {start|stop|restart}"
	    exit 1
esac
